package com.xtoad.ecms.common.web.interceptor;

import com.xtoad.ecms.common.web.base.Result;
import com.xtoad.ecms.common.web.exception.BusinessException;
import com.xtoad.ecms.common.web.exception.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常捕捉处理
 *
 * @author xtoad
 * @date 2020/05/29
 */
@ControllerAdvice
public class GlobalExceptionInterceptor {

    private final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionInterceptor.class);

    /**
     * 全局业务异常捕捉处理
     *
     * @param ex 业务异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Result businessExceptionHandler(BusinessException ex) {
        LOGGER.info(ex.getCode(), ex.getMsg());
        return Result.failed(ex.getCode(), ex.getMsg());
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex Exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception ex) {
        LOGGER.error(ResultCodeEnum.UNKNOWN_ERROR.getMsg(), ex);
        if (ex instanceof  MethodArgumentNotValidException) {
            return Result.failed(ResultCodeEnum.INVALID_PARAMETER);
        }

        return Result.failed(ResultCodeEnum.UNKNOWN_ERROR);
    }
}